package com.cn.gmall.activity.redis;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;



@Configuration
public class RedisChannelConfig {
    /**
     *  订阅主题
     *
     * @param redisConnectionFactory 链接工厂
     * @param listenerAdapter 监听器适配器
     * @return
     */

    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory redisConnectionFactory,
                                                   MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer redisContainer = new RedisMessageListenerContainer();
        //设置链接工厂
        redisContainer.setConnectionFactory(redisConnectionFactory);
//     监听器适配器
        redisContainer.addMessageListener(listenerAdapter, new PatternTopic("seckillPush")); //监听规则

        return redisContainer;
    }

    /**
     * 监听器适配器 按监听规则 监听到消息后执行->receiverMessage
     * @param receiverMessage 自定义消费对象 (监听后 该执行什么)
     * @return
     */
    @Bean
    public MessageListenerAdapter listenerAdapter(ReceiverMessage receiverMessage) {
        //反射---CLASS对象---method --方法执行
        return new MessageListenerAdapter(receiverMessage, "messageReceive");
    }

    /***
     *   和redisUtil 里面的redis不能重名    template
     * @param factory StringRedisTemplate能使用工厂 -------- RedisTemplate不能用
     * @return
     */
    @Bean
    public StringRedisTemplate template(RedisConnectionFactory factory){

        return new StringRedisTemplate(factory);
    }

}
